package com.juyu.miliao.scheduler.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.juyu.miliao.scheduler.dao.mysql.OrderDao;
import com.juyu.miliao.scheduler.domin.Order;

@Component
public class PayNotifySGScheduler {
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	@Resource
	private OrderDao orderDao;

	private final Logger logger = LoggerFactory.getLogger(PayNotifySGScheduler.class);
//	private static final String sg_notify_url = "http://pay.c6829063.com:30002/sg-pay/miLiao";

	// 60秒发送一次同步消息
//	@Scheduled(fixedDelay = 1000 * 60, initialDelay = 1000 * 40)
	public void payNotifySGScheduler() throws Exception {
		String nowDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		logger.info("定时任务payNotifySGScheduler开始：time={}", nowDateTime);
		Map<Object, Object> map = stringRedisTemplate.opsForHash().entries("payNotifySG");
		map.forEach((key, value) -> {
			Optional<Order> optOrder = Optional.ofNullable(orderDao.findOrderByOrderId(key.toString()));
			if (!optOrder.isPresent()) {
				stringRedisTemplate.opsForHash().delete("payNotifySG",key);
				logger.error("同步给单机后台数据错误----数据不存在----orderId={}",key);
			}else{
				JSONObject jsonObject = JSONObject.parseObject(value.toString());
				String accessUrl = jsonObject.get("accessUrl").toString();
				int notifyNum = Integer.parseInt(jsonObject.get("notifyNum").toString());
				String responseStr= doGet(accessUrl);
				stringRedisTemplate.opsForHash().delete("payNotifySG",key);
				if(!responseStr.equals("ok") && notifyNum - 1 > 0){
					JSONObject json = new JSONObject();
					json.put("accessUrl",accessUrl);
					json.put("notifyNum",notifyNum-1);
					stringRedisTemplate.opsForHash().put("payNotifySG", key, json.toString());
				}
			}
		});
		logger.info("定时任务payNotifySGScheduler结束：time={}",
				LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
	}

	private String doGet(String accessUrl) {
		String response = null;
		HttpURLConnection httpURLConnection = null;
		BufferedReader br = null;
		try {
			logger.info("开始同步给单机后台数据----开始调用get请求:下单地址----url={}", accessUrl);
			URL url = new URL(accessUrl);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			String readLine = null;
			StringBuffer sb = new StringBuffer();
			while ((readLine = br.readLine()) != null) {
				sb.append(readLine);
			}
			response = sb.toString();
		} catch (Exception e) {
			logger.info("开始同步给单机后台数据----开始调用get请求:请求异常----", e);
		} finally {
			httpURLConnection.disconnect();
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return response;
	}
}
